package com.paipai.consumer;

import com.alibaba.fastjson.JSONObject;
import com.paipai.dto.Auction;
import com.paipai.entity.POrder;
import com.paipai.entity.Round;
import com.paipai.service.OrderService;
import com.paipai.service.RoundService;
import com.paipai.utils.IdWorker;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

@Component
public class DelayDeadSaleMqConsumer {
    @Autowired
    RoundService roundService;
    @Autowired
    OrderService orderService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    StringRedisTemplate redisTemplate;

    @RabbitListener(queues = "deadLetterQueue")
    public void onMsg(Round round, Message message, Channel channel) throws IOException {
        System.out.println("传进队列中的round"+round);
        //拿到当前时间和到期时间做比较。如果当前时间大于或等于到期时间说明不再返回队列
        //执行流拍或者生成订单
        //当前时间
        long now = System.currentTimeMillis();
        //持续天数
        long days = Integer.parseInt(round.getDuration());
        //到期时间
        long endTime = round.getStarttime().getTime() + days * 1000 * 60;
        HashOperations ops = redisTemplate.opsForHash();
        Map<String, Auction> entries = ops.entries(round.getId() + "");
        try {
            if (now >= endTime) {
                //查看买家id是否为空
                if (0 == entries.size()) {
                    System.out.println("流拍了============");
                    //执行流拍
                    roundService.deadSale(round);
                } else {
                    System.out.println("去生成订单了===========");
                    //生成订单。出价信息从redis中获取
                    POrder order = new POrder();
                    IdWorker idWorker = new IdWorker(1, 1, 1);
                    order.setId(idWorker.nextId());
                    //测试买家id=1 实际从redis中获取(key是场次id ，value中出价最高的id)
                    //用来装所有的出价
                    List<Auction> list = new ArrayList<>();
                    Set<Map.Entry<String, Auction>> entrySet = entries.entrySet();
                    for (Map.Entry<String, Auction> auctionEntry : entrySet) {
                        Auction auction = JSONObject.parseObject(auctionEntry.getValue() + "", Auction.class);
                        list.add(auction);
                    }
                    list.sort((o1, o2) -> {
                        //比较所有的出价 降序
                        return Integer.parseInt(o2.getOfferPrice().subtract(o1.getOfferPrice()).toString());
                    });
                    //排序后拿到最高竞价
                    Auction auction = list.get(0);
                    order.setBuyerId(auction.getBuyerId());
                    order.setProductId(round.getProductid());
                    order.setSellerId(round.getSalerid());
                    //测试插入订单金额 实际从redis中获取(key是场次id ，value中出价最高)
                    order.setPrice(auction.getOfferPrice());
                    order.setCreatTime(new Date());
                    order.setUpdateTime(new Date());
                    //通过买家id查出用户的地址(先为空)             ****地址待添加!****
                    //设置状态待付款
                    order.setState(1);
                    //生成订单
                    orderService.insertOrder(order);
                    roundService.endSale(round,auction.getBuyerId(),auction.getOfferPrice());
                }

            } else {
                //回到队列中
                System.out.println("未到时间========重新归队");
                rabbitTemplate.convertAndSend("normalExchange", "normalRoutingKey", round);
            }
            System.out.println("手动ack了================");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }

    }
}